package com.zyong.design.pattern.interpret.case1;

import java.util.Stack;

/**
 * 上下文环境角色
 * @program: zyong-design-pattern
 * @ClassName: ExpressionContext
 * @author: zyong
 * @create: 2024-06-01 20:37
 */
public class ExpressionContext {
    private Stack<IExpression> stack = new Stack<>();

    public ExpressionContext(String expression) {
        // 解析表达式
        this.parse(expression);
    }

    /**
     * 解析表达式
     * @param expression
     */
    private void parse(String expression) {
        String[] elementArray = expression.split(" ");
        for (int i = 0; i < elementArray.length; i++) {
            String element = elementArray[i];
            if (element.equals("+")) {
                // 栈内元素出栈
                IExpression leftExpression = stack.pop();
                // 取出+号后的下一个元素
                IExpression rightExpression = new NumberExpression(elementArray[++i]);

                IExpression addExpression = new AddExpression(leftExpression, rightExpression);

                // 将计算结果入栈
                stack.push(new NumberExpression(addExpression.interpret() + ""));
            } else if (element.equals("-")) {
                // 栈内元素出栈
                IExpression leftExpression = stack.pop();
                // 取出+号后的下一个元素
                IExpression rightExpression = new NumberExpression(elementArray[++i]);

                IExpression subExpression = new SubExpression(leftExpression, rightExpression);

                // 将计算结果入栈
                stack.push(new NumberExpression(subExpression.interpret() + ""));
            } else {
                // 如果是数字则直接入栈
                stack.push(new NumberExpression(element));
            }
        }
    }

    public int calculate() {
        // 经过前面解析，到这里stack内只会剩下唯一一个数字，即运算结果
        return stack.pop().interpret();
    }

}
